package com.flyan.game.motafx.core.algorithm;

import com.flyan.game.motafx.core.pojo.LifePanel;

/**
 * 战斗算法
 *
 * @author flyan
 * @version 1.0
 * @email flyan_by_chenu@sina.com
 * @since 2025/2/5
 */
public class BattleAlgorithm {

    /**
     * 攻击者
     */
    private Battler attacker;

    /**
     * 攻击目标
     */
    private Battler target;

    public BattleAlgorithm(Battler attacker, Battler target) {
        this.attacker = attacker;
        this.target = target;
    }

    public BattleResult getBattleResult() {
        BattleResult battleResult = new BattleResult(attacker, target);
        battleResult.setCanBatter(true);

        /* 初始化生命面板 */
        attacker.initLifePanel();
        target.initLifePanel();

        /* 检查是否可破防 */
        if (attacker.getLifePanel().getAck() <= target.getLifePanel().getDef()) {
            battleResult.setCanBatter(false);
            battleResult.setNotCanBatterReason("不可战斗：未破防！");
            return battleResult;
        }

        /* 只要双方都活着，不死不休一直战斗 */
        Battler att = attacker; // 先攻
        Battler def = target;
        Battler tmp;
        while (!attacker.getLifePanel().isDead() && !target.getLifePanel().isDead()) {
            LifePanel attLp = att.getLifePanel();
            LifePanel defLp = def.getLifePanel();
            int damage = Math.max(attLp.getAck() - defLp.getDef(), 0);
            BattleResult.Event event = new BattleResult.Event(att, def, damage);
            battleResult.addEvent(event);

            /* 减少防御方 hp */
            defLp.setHp(Math.max(defLp.getHp() - damage, 0));
            event.setTargetHp(defLp.getHp());

            /* 此轮交战结束，攻守互换 */
            tmp = att;
            att = def;
            def = tmp;
        }

        /* 胜利者掠夺失败者的一切 */
        if (attacker.getLifePanel().isDead()) {
            battleResult.setWinner(target);
            target.getLifePanel().setGold(target.getLifePanel().getGold() + attacker.getLifePanel().getGold());
        } else if (target.getLifePanel().isDead()) {
            battleResult.setWinner(attacker);
            attacker.getLifePanel().setGold(attacker.getLifePanel().getGold() + target.getLifePanel().getGold());
        }

        return battleResult;
    }

}
